import Vue from 'vue'
import Router from 'vue-router'
import store from '../store/index'
import { BASE_URL } from '../config'
import { getToken } from '../utils'
import { getPath } from '../utils/location'
import { mine } from './user'
import App from '../main'

// 首页
const Index = () => import('../views/index.vue')

// 登录
const Login = () => import('../views/login.vue')

// 404
const Page404 = () => import('../views/404.vue')

Vue.use(Router)

/**
 * @desc BeforeEnter 回调
 * @isDone {boolean} mbtiDone, mssmDone
 * @action {string} store.dispatch(action)
 * @nextRoute {object}
 * @next {fn}
 */
const router = new Router({
  mode: 'history',
  base: BASE_URL,
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      const position = {x: 0, y: 0}
      let matched = to.matched
      if (matched.some(item => item.meta.scrollToTop === false)) {
        delete position.x
        delete position.y
      }
      if (to.hash) {
        position.selector = to.hash
      }
      return position
    }
  },
  linkActiveClass: 'active',
  linkExactActiveClass: 'exact-active',
  routes: [
    {
      path: '/',
      alias: '/index',
      name: 'Index',
      component: Index,
      meta: {title: '欢迎', asideIndex: '0'}
    },
    // 我的设置
    ...mine,
    {
      path: 'login',
      name: 'Login',
      component: Login,
      meta: {
        auth: false
      }
    },
    {
      path: '404',
      name: '404',
      component: Page404,
      meta: {
        auth: false
      }
    }
  ]
})

router.beforeEach(function (to, from, next) {
  if (App && App.$Progress) {
    App.$Progress.start()
  }
  if (to.name == null) {
    next({path: '/'})
    return false
  }
  if (to.meta.auth === false) {
    next()
  } else {
    if (getToken()) {
      next()
    } else {
      next({name: 'Login', query: {from: from.query.from || getPath()}})
    }
  }
  store.commit('common/updateAsideActive', to.meta.asideIndex)
  next()
})

router.afterEach(function (to) {
  if (App && App.$Progress) {
    App.$Progress.finish()
  }
  // 统计代码
  // /* global _hmt */
  // _hmt.push(['_trackPageview', to.fullPath])
})

export default router
